// server.js
const Koa = require('koa');
const WebSocket = require('ws');
const app = new Koa();
const path = require('path');
const Router = require('koa-router');
const wss = new WebSocket.Server({ noServer: true });
const router = new Router();
const render = require('koa-art-template')


render(app, {
  root: path.join(__dirname, 'views'),   // 视图的位置
  extname: '.html',  // 后缀名 如：index.html
  debug: process.env.NODE_ENV !== 'production'  //是否开启调试模式
});

router.get('/t', async (ctx) => {
  await ctx.render('index')
})

app.use(router.routes());   /*启动路由*/
app.use(router.allowedMethods());

wss.on('connection', (ws) => {
  console.log('Client connected');

  ws.on('message', (message) => {
    const data = JSON.parse(message);
    // 广播消息给所有其他客户端
    wss.clients.forEach((client) => {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(JSON.stringify(data));
      }
    });
  });

  ws.on('close', () => {
    console.log('Client disconnected');
  });
});

const PORT = process.env.PORT || 1111;
const server = require('http').createServer(app.callback());
server.on('upgrade', (request, socket, head) => {
  wss.handleUpgrade(request, socket, head, (ws) => {
    wss.emit('connection', ws, request);
  });
});
server.listen(PORT, () => {
  console.log(`WebSocket server is running on port ${PORT}`);
});
